package org.kong.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.kong.pojo.dto.SysRoleDTO;
import org.kong.pojo.dto.SysRoleUpdateDTO;
import org.kong.pojo.entity.SysRole;
import org.kong.service.RoleService;
import org.kong.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 加油
 *
 * @author konglingfeng
 * @date 2025/8/22
 * @desc
 */
@RestController
@RequestMapping("/role")
@CrossOrigin
@Slf4j
public class RoleController {
    @Autowired
    private RoleService roleService;

    /**
     * 角色列表
     */
    @GetMapping("/list")
    public Result<PageInfo<SysRole>> list(SysRoleDTO sysRoleDTO) {
        PageHelper.startPage(sysRoleDTO.getPageNum(), sysRoleDTO.getPageSize());
        List<SysRole> list = roleService.list(sysRoleDTO);
        PageInfo<SysRole> pageInfo = new PageInfo<>(list);
        log.info("查询角色列表：{}", pageInfo);
        if (list.isEmpty()) {
            return Result.error("查询失败");
        }
        return Result.success("查询成功",pageInfo);
    }

    /**
     * 删除角色
     */
    @GetMapping("/delete/{id}")

    public Result<String> delete(@PathVariable Integer id) {
        log.info("删除角色：{}", id);
        try {
            roleService.delete(id);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除失败");
        }
        return Result.success("删除成功");

    }

    /**
     * 批量删除角色
     */
    @GetMapping("/deleteBatch/{ids}")
    @Transactional
    public Result<String> deleteBatch(@PathVariable List<Integer> ids) {
        log.info("删除角色：{}", ids);
        try {
            roleService.deleteBatch(ids);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除失败");
        }
        return Result.success("删除成功");
    }

    /**
     * 通过角色id查询角色的权限
     */
    @GetMapping("/permIds/{id}")
    public Result<List<Integer>> listByRoleId(@PathVariable Integer id) {
        List<Integer> list = roleService.listByRoleId(id);

        return Result.success("查询成功",list);
    }

    /**
     * 更新角色信息
     */
    @PostMapping("role/update")
    public Result<String> update(@RequestBody SysRoleUpdateDTO sysRoleUpdateDTO) {
        boolean isSuccess = roleService.update(sysRoleUpdateDTO);
        if (isSuccess) {
            return Result.success("更新成功");
        }
        return Result.error("更新失败");
    }

    /**
     * 新增角色
     */
    @PostMapping("/add")
    public Result<String> add(@RequestBody SysRoleUpdateDTO sysRoleUpdateDTO) {
        roleService.add(sysRoleUpdateDTO);

        return Result.success("新增成功");

    }

}
